<template>
    <!--选择图片-->
    <div class="ui-picture">
        <div class="ui-tags ui-image-tabs">
            <el-tabs v-model="activeName" @tab-click="handleTagsClick">
                <el-tab-pane label="商家图片" name="ONGOING">
                    <div class="ui-picture-content">
                        <div class="ui-picture-left">
                            <!--<div class="ui-picture-search">
                                <el-input
                                placeholder="请输入分组名称"
                                v-model="groupName">
                                <i slot="prefix" class="el-input__icon el-icon-search" style="cursor: pointer;"></i>
                                </el-input>
                            </div>-->
                            <div class="ui-picture-type">
                                <el-scrollbar style="height:100%;">
                                    <div
                                        @click="changeType(index)"
                                        v-for="(item, index) of allImageGroup"
                                        :key="index"
                                        class="ui-group-item"
                                        :class="{ 'ui-choose-item': index === typeIndex }"
                                    >
                                        {{ item.groupName }}
                                        <span v-if="index === typeIndex" style="margin-left:10px;"
                                            >({{
                                                tableData.page.Allpage !== undefined
                                                    ? tableData.page.Allpage
                                                    : 0
                                            }})</span
                                        >
                                        <i
                                            v-if="item.id !== '-1' && item.id !== '0'"
                                            class="fa fa-trash"
                                            style="color:#bbb;float:right;"
                                            @click="confirmDeleteOneGroup(item.id)"
                                        ></i>
                                        <el-popover placement="bottom" width="310" trigger="click">
                                            <el-form
                                                ref="editGroupForm"
                                                :model="editGroupForm"
                                                :rules="formRules"
                                                label-width="0"
                                                style="padding:28px 30px;"
                                            >
                                                <el-form-item label="" prop="groupName">
                                                    <el-input
                                                        v-model="editGroupForm.groupName"
                                                        placeholder="请输入分组名称"
                                                    />
                                                </el-form-item>
                                                <div style="text-align: center;">
                                                    <el-button
                                                        @click="submitEditGroup"
                                                        type="primary"
                                                        style="margin-top:10px;width:80px;height:30px;padding:0;"
                                                        >确认</el-button
                                                    >
                                                    <el-button
                                                        @click="closeEditPopover"
                                                        style="margin-top:10px;width:80px;height:30px;padding:0;"
                                                        >取消</el-button
                                                    >
                                                </div>
                                            </el-form>
                                            <i
                                                v-if="item.id !== '-1' && item.id !== '0'"
                                                class="fa fa-edit"
                                                style="color:#bbb;float:right;margin-right:5px;margin-top: 1px;"
                                                slot="reference"
                                                @click.stop="openEditGroup(item.id)"
                                            ></i>
                                        </el-popover>
                                    </div>
                                    <el-popover
                                        placement="bottom"
                                        width="310"
                                        :ref="`popover1`"
                                        trigger="click"
                                    >
                                        <el-form
                                            ref="groupForm"
                                            :model="groupForm"
                                            :rules="formRules"
                                            label-width="0"
                                            style="padding:28px 30px;"
                                        >
                                            <el-form-item label="" prop="groupName">
                                                <el-input
                                                    v-model="groupForm.groupName"
                                                    placeholder="请输入分组名称"
                                                />
                                            </el-form-item>
                                            <div style="text-align: center;">
                                                <el-button
                                                    @click="submitGroup"
                                                    type="primary"
                                                    style="margin-top:10px;width:80px;height:30px;padding:0;"
                                                    >确认</el-button
                                                >
                                                <el-button
                                                    @click="closePopover"
                                                    style="margin-top:10px;width:80px;height:30px;padding:0;"
                                                    >取消</el-button
                                                >
                                            </div>
                                        </el-form>
                                        <el-button
                                            slot="reference"
                                            class="ui-operation-button"
                                            style="margin-top:5px;"
                                            ><i class="fa fa-plus" style="margin-right:5px;"></i
                                            >添加分组</el-button
                                        >
                                    </el-popover>
                                </el-scrollbar>
                            </div>
                        </div>
                        <div class="ui-picture-right">
                            <div class="ui-search">
                                <div class="ui-search-display">
                                    <el-button
                                        @click="openImgDialog"
                                        type="primary"
                                        style="width:80px;height:30px;padding:0;font-size: 13px;margin-left:10px;"
                                        ><i class="fa fa-plus" style="margin-right:5px;"></i
                                        >上传图片</el-button
                                    >
                                </div>
                                <div class="ui-search-input">
                                    <el-input
                                        placeholder="请输入图片名称"
                                        v-model="searchModel.name"
                                    >
                                        <el-button slot="append" @click="search()">查询</el-button>
                                    </el-input>
                                </div>
                            </div>
                            <div class="ui-pic-list">
                                <el-scrollbar style="height:100%;">
                                    <div class="ui-pic-item-list">
                                        <el-radio-group v-model="chooseImage">
                                            <div
                                                class="ui-pic-item-list-item"
                                                v-for="(item, index) of tableData.data"
                                                :key="index"
                                                @click="chooseOneImg(item.url)"
                                            >
                                                <div
                                                    class="ui-pic-item-list-img"
                                                    :style="{
                                                        'background-image': 'url(' + item.url + ')'
                                                    }"
                                                ></div>
                                                <!--<div class="ui-pic-item-list-text">{{item.fileName}}</div>
                        <div class="ui-select-mask" v-if="picId === item.id">
                          <img src="../../assets/basic/pictureChoose.png">
                        </div>-->
                                                <div class="ui-pic-item-list-text">
                                                    <el-radio :label="item.url">{{ '' }}</el-radio
                                                    >{{ item.fileName }}
                                                </div>
                                                <div class="ui-pic-item-list-size">
                                                    <div class="ui-pic-item-list-size-filesize">
                                                        {{ item.fileSize }}
                                                    </div>
                                                    <div class="ui-pic-item-list-size-date">
                                                        {{ item.createTime.split(' ')[0] }}上传
                                                    </div>
                                                </div>
                                            </div>
                                        </el-radio-group>
                                    </div>
                                </el-scrollbar>
                            </div>
                            <div class="ui-pic-bottom">
                                <!--<el-button @click="openImgDialog" type="primary" style="width:80px;height:30px;padding:0;font-size: 13px;"><i class="fa fa-plus" style="margin-right:5px;"></i>上传图片</el-button>-->
                                <div class="ui-pagination">
                                    <el-pagination
                                        background
                                        v-on:size-change="tableData.page.handleSizeChange"
                                        v-on:current-change="tableData.page.handleCurrentChange"
                                        v-bind:current-page="
                                            tableData.page.CurrentPage
                                                ? tableData.page.currentPage
                                                : 1
                                        "
                                        v-bind:page-size="tableData.page.pagesize"
                                        layout="total,prev, pager, next"
                                        v-bind:total="tableData.page.Allpage"
                                        v-if="tableData.isPage"
                                    >
                                    </el-pagination>
                                </div>
                            </div>
                            <div class="ui-picture-bottom">
                                <div class="ui-choose-button">
                                    <el-button type="primary" class="ui-button" @click="confirmImg"
                                        >确定</el-button
                                    >
                                    <el-button class="ui-button" @click="cancleImg">取消</el-button>
                                </div>
                            </div>
                        </div>
                    </div>
                </el-tab-pane>
            </el-tabs>
        </div>

        <!--上传图片-->
        <div v-if="uploadImageVisible">
            <el-dialog
                title="上传图片"
                :visible.sync="uploadImageVisible"
                :modal-append-to-body="false"
                width="590px"
                height="300px"
            >
                <div style="padding:30px 20px;box-sizing: border-box;">
                    <upload-image @refresh="refreshImg" @close="closeDialog"></upload-image>
                </div>
            </el-dialog>
        </div>
    </div>
</template>

<script>
import {
    uploadImage,
    queryConditionList,
    queryAllImageGroup,
    createImageGroup,
    updateImageGroup,
    moveToImage,
    batchDeleteImage,
    deleteImage,
    updateImageName,
    deleteImageGroup
} from '@/api/image';
import { alertSuccess, alertError, alertWarning, formatTime } from '@/utils/index';
import UploadImage from './uploadImage';
export default {
    components: {
        UploadImage
    },
    data() {
        return {
            fileList: [],
            allImageGroup: [],
            uploadImageVisible: false,
            url: require('../../assets/basic/timg111.jpg'),
            typeIndex: 0,
            activeName: 'ONGOING',
            chooseImage: '',
            groupName: '',
            picName: '',
            picId: '',
            imgIndex: 0,
            typeList: [
                {
                    groupName: '全部分组',
                    id: '-1'
                },
                {
                    groupName: '未分组',
                    id: '0'
                }
            ],
            groupList: [],
            groupForm: {
                groupName: ''
            },
            editGroupForm: {
                id: '',
                groupName: ''
            },
            formRules: {
                groupName: [{ required: true, trigger: 'blur', message: '请输入分组名称' }]
            },
            moveForm: {
                groupId: '',
                ids: []
            },
            moveFormRules: {
                groupId: [{ required: true, trigger: 'change', message: '请输入分组' }]
            },
            tableData: {
                data: [],
                isPage: false,
                multipleSelection: [],
                page: {}
            },
            searchModel: {
                groupId: '',
                isFull: 1,
                name: '',
                pageNum: 1,
                pageSize: 12,
                countSql: true,
                reasonable: true
            },
            pageOptions: {
                currentChageFlag: false
            },
            allSystemImageGroup: []
        };
    },
    methods: {
        // *********************************** 公共方法 *****************************************
        filterNullFields(options) {
            // 删除空字段
            let param = Object.assign(options);
            if (Object.keys.length > 0) {
                for (let key in param) {
                    if (!param[key] && param[key] !== 0) {
                        delete param[key];
                    }
                }
            }
            return param;
        },
        getQueryParam(value) {
            // 获取查询字段参数 ٩(๑❛ᴗ❛๑)۶
            let model = this.searchModel;
            let options = {};
            for (const key in model) {
                if (key !== 'checkInTime') {
                    Object.assign(options, { [key]: model[key] });
                }
                delete model.currentPage;
            }
            let time = {};
            if (Array.isArray(model.checkInTime) && model.checkInTime.length) {
                time = {
                    startRegTime: formatTime(new Date(model.checkInTime[0])),
                    endRegTime: formatTime(new Date(model.checkInTime[1]))
                };
            }
            let param = Object.assign({}, time, options, value);
            return this.filterNullFields(param);
        },
        // *********************************** 页面逻辑 *****************************************
        initPageData() {
            // 初始化页面数据 包括下拉菜单的选项以及表格数据
            // 这个参数拿的也太费劲了╭(╬◣д◢) 必须写在setTimeout里 否则娶不到model下的数据(╰_╯)#会报错
            setTimeout(() => {
                let initTableParm = { ...{ pageNum: 1, pageSize: 12 } };
                Promise.all([
                    this.getAllImageGroup(),
                    this.getTableData(this.getQueryParam(initTableParm))
                ])
                    .then(res => {})
                    .catch(err => {
                        console.log('err', err);
                    });
            });
        },
        getTableData(options) {
            // 获取表格初始数据 模拟请求回来的数据
            queryConditionList(options)
                .then(res => {
                    // 请求接口
                    if (res.data.success) {
                        let total = res.extra === undefined ? 0 : res.extra.total;
                        if (res.extra !== undefined && res.extra.total) {
                            // 总数存在的话 加分页
                            this.tableData.isPage = true;
                        } else {
                            this.tableData.isPage = false;
                        }
                        this.tableData.page = {
                            currentPage: parseInt(this.searchModel.pageNum, 10),
                            pagesize: this.searchModel.pageSize,
                            handleSizeChange: this.handleSizeChange, // 分页条数改变触发该函数
                            handleCurrentChange: this.handleCurrentChange, // 当前页码改变触发改函数
                            Allpage: total
                        };

                        this.pageOptions.currentChageFlag = false; // 防止点击分页条数时多次触发提交请求
                        let content = res.data.data;
                        this.tableData.data = content;
                    }
                })
                .catch(err => {
                    console.log('err', err);
                });
        },
        handleSizeChange(val) {
            // 分页条数改变触发该函数
            this.pageOptions.currentChageFlag = true;
            let handlesize = this.getQueryParam({ ...{ pageSize: val, pageNum: 1 } });
            this.searchModel.pageNum = 1;
            this.searchModel.pageSize = val;
            this.getTableData(handlesize);
        },
        handleCurrentChange(val) {
            // 当前页码改变触发改函数
            if (!this.pageOptions.currentChageFlag) {
                const pagesize = this.tableData.page.pagesize;
                let handlesize = this.getQueryParam({ ...{ pageNum: val, pageSize: pagesize } });
                this.searchModel.pageNum = val;
                this.searchModel.pageSize = pagesize;
                this.getTableData(handlesize);
            }
        },

        handleChange(file, fileList) {
            let image = file.raw;
            let fileName = file.name;
            let obj = {
                file: image,
                fileName: fileName
            };
            let array = [];
            array.push(obj);
            let data = {
                files: array,
                groupId: this.searchModel.groupId
            };
            uploadImage(this.filterNullFields(data))
                .then(res => {
                    // 请求接口
                    if (res.data.success) {
                        alertSuccess('添加图片成功', this);
                        this.getTableData(this.getQueryParam({ pageNum: 1, pageSize: 12 }));
                    } else {
                        alertError(res.data.msg, this);
                    }
                })
                .catch(err => {
                    alertError('修改会员等级失败', this);
                    console.log('err', err);
                });
        },
        getAllImageGroup() {
            queryAllImageGroup()
                .then(res => {
                    // 请求接口
                    if (res.data.success) {
                        this.allImageGroup = this.typeList.concat(res.data.data);
                        this.groupList = res.data.data;
                    } else {
                        alertError(res.data.msg, this);
                    }
                })
                .catch(err => {
                    console.log('err', err);
                });
        },
        refreshImg() {
            this.getTableData(this.getQueryParam({ pageNum: 1, pageSize: 12 }));
            this.uploadImageVisible = false;
        },
        closeDialog() {
            this.uploadImageVisible = false;
        },
        openImgDialog() {
            this.uploadImageVisible = true;
        },
        changeType(index) {
            this.typeIndex = index;
            let obj = this.allImageGroup[index];
            if (obj.id === '-1') {
                this.searchModel.groupId = '';
                this.searchModel.isFull = 1;
            } else if (obj.id === '0') {
                this.searchModel.groupId = '';
                this.searchModel.isFull = 0;
            } else {
                this.searchModel.groupId = obj.id;
                this.searchModel.isFull = 0;
            }
            this.getTableData(this.getQueryParam({ pageNum: 1, pageSize: 12 }));
        },
        chooseImg(id, index) {
            if (this.picId === id) {
                this.picId = '';
            } else {
                this.picId = id;
                this.imgIndex = index;
            }
        },
        chooseOneImg(url) {
            this.chooseImage = url;
        },
        confirmImg() {
            if (this.chooseImage !== '') {
                this.$emit('select', this.chooseImage);
            } else {
                alertWarning('请选择图片', this);
            }
        },
        cancleImg() {
            this.chooseImage = '';
            this.$emit('close');
        },
        handleTagsClick(tab, event) {
            if (tab.name === 'ONGOING') {
            } else if (tab.name === 'UNSTART') {
            }
        },
        search() {
            this.getTableData(this.getQueryParam({ pageNum: 1, pageSize: 12 }));
        },
        //确认删除分组
        confirmDeleteOneGroup(id) {
            this.$confirm('确认删除该分组?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            })
                .then(() => {
                    this.deleteOneGroup(id);
                })
                .catch(() => {});
        },
        //删除一个分组
        deleteOneGroup(id) {
            let data = {
                id: id
            };
            deleteImageGroup(data)
                .then(res => {
                    if (res.data.success) {
                        alertSuccess('分组删除成功', this);
                        this.getAllImageGroup();
                        if (this.searchModel.groupId === id) {
                            this.searchModel.groupId = '';
                            this.searchModel.isFull = 1;
                        }
                        this.getTableData(this.getQueryParam());
                    } else {
                        alertError(res.data.msg, this);
                    }
                })
                .catch(error => {
                    alertError('分组删除失败', this);
                });
        },
        openEditGroup(id) {
            this.allImageGroup.forEach((item, index) => {
                if (item.id === id) {
                    Object.assign(this.editGroupForm, {
                        id: id,
                        groupName: item.groupName
                    });
                }
            });
        },
        closePopover() {
            this.$refs.popover1.doClose();
            this.$refs.groupForm.resetFields();
        },
        closePopover3() {
            this.$refs.popover3.doClose();
            this.$refs.moveForm.resetFields();
        },
        closeEditPopover() {
            document.querySelector('.ui-normal-test').click();
        },
        submitGroup() {
            this.$refs.groupForm.validate(valid => {
                if (valid) {
                    var data = JSON.parse(JSON.stringify(this.groupForm));
                    createImageGroup(this.filterNullFields(data))
                        .then(res => {
                            if (res.data.success) {
                                alertSuccess('添加分组成功', this);
                                this.getAllImageGroup();
                                this.closePopover();
                            } else {
                                alertError(res.data.msg, this);
                                this.loading = false;
                            }
                        })
                        .catch(error => {
                            alertError('添加分组失败', this);
                            this.loading = false;
                        });
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        submitEditGroup() {
            var data = JSON.parse(JSON.stringify(this.editGroupForm));
            updateImageGroup(this.filterNullFields(data))
                .then(res => {
                    if (res.data.success) {
                        alertSuccess('更新分组成功', this);
                        this.getAllImageGroup();
                        this.closeEditPopover();
                    } else {
                        alertError(res.data.msg, this);
                        this.loading = false;
                    }
                })
                .catch(error => {
                    alertError('更新分组失败', this);
                    this.loading = false;
                });
        },
        submitMoveGroup() {
            if (this.checkList.length === 0) {
                alertWarning('请选择图片', this);
            } else {
                this.$refs.moveForm.validate(valid => {
                    if (valid) {
                        var data = JSON.parse(JSON.stringify(this.moveForm));
                        data.ids = this.checkList;
                        moveToImage(this.filterNullFields(data))
                            .then(res => {
                                if (res.data.success) {
                                    alertSuccess('移动分组成功', this);
                                    this.closePopover3();
                                    this.getTableData(this.getQueryParam());
                                } else {
                                    alertError(res.data.msg, this);
                                    this.loading = false;
                                }
                            })
                            .catch(error => {
                                alertError('移动分组失败', this);
                                this.loading = false;
                            });
                    } else {
                        console.log('error submit!!');
                        return false;
                    }
                });
            }
        }
    },
    mounted() {
        this.initPageData();
    },
    computed: {},
    watch: {}
};
</script>
<style lang="scss">
.ui-picture-search .el-input__icon {
    line-height: 30px !important;
}
.ui-picture-search .el-input__inner {
    padding-right: 2px !important;
    font-size: 12px !important;
}
.ui-pic-list .el-scrollbar {
    padding-bottom: 0 !important;
}
.ui-tags .el-tabs__nav-wrap::after {
    background-color: transparent !important;
}
.ui-tags .el-tabs__nav-scroll {
    box-sizing: border-box;
    margin-top: 0;
}
.ui-image-tabs .el-tabs__nav-scroll {
    margin-bottom: 0 !important;
}
.ui-tags .el-tabs__item {
    height: 34px !important;
    line-height: 34px !important;
}
.ui-tags .el-tabs__active-bar {
    height: 4px !important;
}
.ui-tags .el-tabs__content {
    width: calc(100% + 30px);
    margin-left: -15px;
}
.ui-pic-item-list .el-radio-group {
    width: 100%;
}
</style>
<style scoped lang="scss">
.ui-picture {
    width: calc(100% + 40px);
    margin-left: -20px;
    margin-top: -30px;
    margin-bottom: -30px;
    height: 600px;
    .ui-picture-content {
        width: 100%;
        height: 550px;
        display: flex;
        border-top: 1px solid #eee;
        .ui-picture-left {
            width: 165px;
            height: 100%;
            border-right: 1px solid #eee;
            padding: 20px 15px;
            .ui-picture-search {
                height: 30px;
            }
            .ui-picture-type {
                width: 100%;
                height: calc(100% - 45px);
                .ui-group-item {
                    width: 100%;
                    height: 36px;
                    border-radius: 10px;
                    margin: 1px 0;
                    padding: 12px 20px;
                    box-sizing: border-box;
                    color: #b0aeb5;
                    font-weight: bold;
                    font-size: 12px;
                    cursor: pointer;
                }
                .ui-choose-item {
                    color: #35323b;
                    background: #f2f2f6;
                }
                .ui-group-item:hover {
                    color: #35323b;
                    background: #f2f2f6;
                }
            }
        }
        .ui-picture-right {
            width: calc(100% - 165px);
            height: 100%;
            .ui-operation-button {
                border: 1px solid #3f9eff;
                color: #3f9eff;
                width: 84px;
                height: 28px;
                padding: 0;
                margin-left: 10px;
            }
            .ui-search {
                display: flex;
                height: 60px;
                padding: 0 28px;
                margin-top: 15px;
                .ui-search-display {
                    display: flex;
                    flex: 1;
                    .ui-search-name {
                        height: 28px;
                        line-height: 28px;
                        color: #595961;
                        font-size: 12px;
                        margin-right: 4px;
                    }
                    .ui-search-item {
                        width: 82px;
                        height: 28px;
                        border-radius: 4px;
                        text-align: center;
                        line-height: 28px;
                        color: #595961;
                        font-size: 12px;
                        border: 1px solid #e3e2e5;
                        margin-right: 4px;
                    }
                    .ui-item-choose {
                        background: #3f9eff !important;
                        color: #fff !important;
                    }
                }
            }
            .ui-pic-list {
                width: 100%;
                height: 380px;
                .ui-pic-item-list {
                    padding: 0 25px 20px 25px;
                    box-sizing: border-box;
                    overflow: hidden;
                    .ui-pic-item-list-item {
                        width: calc(25% - 19px);
                        border: 1px solid #eee;
                        float: left;
                        margin-right: 19px;
                        margin-bottom: 20px;
                        cursor: pointer;
                        position: relative;
                        .ui-pic-item-list-img {
                            width: 100%;
                            height: 100px;
                            background-repeat: no-repeat;
                            background-size: cover;
                            background-position: center center;
                            img {
                                width: 100%;
                                height: 100%;
                            }
                        }
                        .ui-pic-item-list-text {
                            width: 100%;
                            height: 24px;
                            line-height: 24px;
                            display: block;
                            white-space: nowrap;
                            overflow: hidden;
                            text-overflow: ellipsis;
                            margin-top: 5px;
                            font-size: 12px;
                            color: #595961;
                            text-align: left;
                            padding-left: 8px;
                            box-sizing: border-box;
                        }
                        .ui-pic-item-list-size {
                            display: flex;
                            padding: 8px 13px;
                            box-sizing: border-box;
                            .ui-pic-item-list-size-filesize {
                                font-size: 11px;
                                color: #999;
                                flex: 1;
                                width: 10px;
                                overflow: hidden;
                                text-overflow: ellipsis;
                                white-space: nowrap;
                            }
                            .ui-pic-item-list-size-date {
                                font-size: 11px;
                                color: #999;
                            }
                        }
                        .ui-select-mask {
                            border-radius: 6px;
                            position: absolute;
                            top: 0;
                            bottom: 0;
                            left: 0;
                            right: 0;
                            background: rgba(0, 0, 0, 0.5);
                            text-align: center;
                            img {
                                position: absolute;
                                top: 50px;
                                left: 45px;
                            }
                        }
                    }
                }
            }
            .ui-pic-bottom {
                width: 100%;
                height: 50px;
                padding: 11px 25px;
                display: flex;
                .ui-button {
                    width: 85px;
                    height: 28px;
                    padding: 0;
                }
                .ui-pagination {
                    flex: 1;
                    text-align: right;
                }
            }
        }
    }
    .ui-picture-bottom {
        width: 100%;
        height: 50px;
        border-top: 1px solid #eee;
        display: flex;
        align-items: center;
        justify-content: center;
        .ui-choose-info {
            color: #bbb !important;
            flex: 1;
            font-size: 12px;
            box-sizing: border-box;
            span {
                padding: 0 10px;
            }
        }
        .ui-choose-button {
            display: flex;
            align-items: center;
            justify-content: center;
            .ui-button {
                width: 60px;
                height: 30px;
                padding: 0;
                margin-right: 10px;
            }
        }
    }
}
.ui-tags {
    padding: 0 15px;
    box-sizing: border-box;
}
</style>
